package plugins.detail;

import kd.bos.base.AbstractBasePlugIn;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.util.EventObject;

/**
 * 基础资料插件
 */
public class CalculateBMI extends AbstractBasePlugIn implements Plugin {
    // 字段标识
    private static final String HEIGHT_FIELD = "dcb4_height";
    private static final String WEIGHT_FIELD = "dcb4_weight";
    private static final String BMI_FIELD = "dcb4_bmi";

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        // 正确注册字段变更监听器 - 使用标准API
        this.addItemClickListeners(HEIGHT_FIELD, WEIGHT_FIELD);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        // 检查是否是身高或体重字段变更
        String fieldKey = e.getProperty().getName();
        if (HEIGHT_FIELD.equals(fieldKey) || WEIGHT_FIELD.equals(fieldKey)) {
            calculateBMI();
        }
    }

    /**
     * 计算BMI指数
     * BMI = 体重(kg) / (身高(m)²)
     */
    private void calculateBMI() {
        // 获取当前身高和体重值
        Double height = (Double) this.getModel().getValue(HEIGHT_FIELD);
        Double weight = (Double) this.getModel().getValue(WEIGHT_FIELD);

        // 校验数据有效性
        if (height == null || weight == null || height <= 0 || weight <= 0) {
            this.getModel().setValue(BMI_FIELD, null); // 清空无效数据
            return;
        }

        // 单位转换：身高从厘米(cm)转换为米(m)
        double heightInMeters = height / 100.0;
        double bmiValue = weight / (heightInMeters * heightInMeters);

        // 设置BMI字段值（保留两位小数）
        this.getModel().setValue(BMI_FIELD, Math.round(bmiValue * 100.0) / 100.0);
    }
}